<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect,
  NUpload,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '对象配置' })
import { router } from '@/router'
const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const { modalAction, handleSave, modalForm, modalFormRef, handleEdit, handleDelete, handleAdd } =
    useCRUD({
      name: '对象',
      initForm: {},
      doCreate: api.createSettingDesigner,
      doUpdate: api.updateSettingDesigner,
      doDelete: api.deleteSettingDesigner,
      refresh: () => $table.value?.handlerefresh(),
    })
const data = reactive({
  token: getToken(),
  uploadAction: base_path + 'api/appointment/designer/file',
  parentData: [],
  designerData:[],
  typeData: [],
  fileList: [],
  upload: null,
  fileListLength: 0,
  CityData: [],
})
onMounted(() => {
  api.getDesignerList().then((res) => (data.designerData.value = res.data))
  api.getSpaceList().then((res) => (data.CityData.value = res.data))
  api.getDesignerTypeList().then((res) => (data.typeData = res.data))
  $table.value?.handleSearch()
})
function  level_format(level){
  let ret = ""
  if (!data.CityData.value) {
    return
  }
  data.CityData.value.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  return ret
}
function  level_format2(level){
  let ret = ""
  if (!data.designerData.value) {
    return
  }
  data.designerData.value.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  return ret
}

//跳转路径
function on_add() {
  router.push('/appointment/settings/designer_add')
}
function on_edit(row) {
  router.push({ path: '/appointment/settings/designer_add', query: { id: row.id } })
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '姓名',
    key: 'name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  // {
  //   title: '称号',
  //   key: 'title',
  //   width: 60,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  //   fixed: 'left',
  // },
  {
    title: '所属门店',
    key: 'space_id',
    width: '90',
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      const roles = row.space_name ?? []
      const group = []
      for (let i = 0; i < roles.length; i++)
        group.push(
          h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => roles[i] })
        )
      return h('span', group)
    },
  },
  {
    title: '角色',
    key: 'type',
    align: 'center',
    width: 60,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => data.typeData[row.type - 1].label }
      )
    },
  },
      {
    title: '子角色',
    key: 'doctor_type',
    width: 90,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      const sku_level = row.doctor_type ?? []
      const group = []
      let level_name = ''
      for (let i = 0; i < sku_level.length; i++) {
        level_name = level_format2(sku_level[i])
        let con = level_name
        group.push(
            h(
                NTag,
                { type: 'primary', size: 'small', bordered: false, style: { margin: '0px 3px' } },
                { default: () => con }
            )
        )
      }
      return h('span', group)
    },
  },
  {
    title: '封面图',
    key: 'picture',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {}, [
        h(NAvatar, {
          src: row.picture,
          width: 30,
          fallbackSrc: default_image,
        }),
      ])
    },
  },
  {
    title: '状态',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    on_edit(row)
                    if (!modalForm.value.files) {
                      modalForm.value.files = []
                    }
                    data.fileList.value = [
                      {
                        id: 1,
                        name: '封面',
                        url: row.picture,
                        status: 'finished',
                      },
                    ]
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/contents/delete']]
                  ),
              default: () => h('div', {}, '确定删除该数据吗?'),
            }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.status = row.status === false ? true : false
  row.publishing = false
  try {
    await api.updateSettingDesigner(row)
    $message?.success(row.status ? '正常' : '禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.status = row.status === false ? true : false
  } finally {
    row.publishing = false
  }
}

const validateAddUser = {
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur'],
    },
  ],
}

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}
</script>

<template>
      <CommonPage show-footer title="对象列表">
        <template #action>
          <NButton v-permission="'post/api/content/contents/create'" type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建对象
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
            ref="$table"
            v-model:query-items="queryItems"
            :columns="columns"
            :get-data="api.getSettingDesigner"
            :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <NInput
                  v-model:value="queryItems.name"
                  clearable
                  type="text"
                  placeholder="请输入名称"
                  @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
          </template>
        </CrudTable>
      </CommonPage>
  <!-- 业务页面 -->
</template>
